package likouJava;

public class 矩阵置零 {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        boolean firstRowZero = false;  //第一行是否为零
        boolean firstColZero = false;  //第一列是否为零

        //判断第一行是否有0
        for (int i = 0; i < n; i++) {
            if(matrix[0][i] == 0){
                firstRowZero = true;
                break;
            }
        }

        //判断第一列是否有0
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0){
                firstColZero = true;
                break;
            }
        }

        //用第一行第一列做标记
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0){
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }

        //根据标记清零
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if(matrix[i][0] == 0 || matrix[0][j] == 0){
                    matrix[i][j] = 0;
                }
            }
        }

        //处理第一行
        if(firstRowZero) {
            for (int j = 0; j < n; j++) {
            matrix[0][j] = 0;
            }
        }

        //处理第一列
        if (firstColZero){
            for (int i = 0; i < m; i++) {
                matrix[i][0] = 0;
            }
        }

    }


}
